package org.agile4j.patterns.proxy.hr;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;


public class UserManager {

	private static final String DBDRIVER = "com.ibm.db2.jcc.DB2Driver" ;
	private static final String DBURL = "jdbc:db2://192.168.137.225:50000/PC" ;
	private static final String DBUSER = "administrator" ;
	private static final String PASSWORD = "neusoft" ;

	
	/**
	 * 根据部门编号取得用户信息
	 * 
	 * @param deptId
	 * @return
	 * @throws Exception
	 */
	public List<UserModelApi> getUserByDeptId(String deptId) throws Exception {
		List<UserModelApi> userList = new ArrayList<UserModelApi>() ;
		String sql = "SELECT t1.userid,t1.name FROM tb_user t1, tb_dept t2 WHERE t1.deptid = t2.deptid and t2.deptid like ? " ;
		Connection conn = null ;
		
		try {
			conn = this.getConnection() ;
			PreparedStatement pstmt = conn.prepareStatement(sql) ;
			pstmt.setString(1, deptId + "%");
			
			ResultSet rs = pstmt.executeQuery() ;
			while(rs.next()){
				// 这里是创建的代理对象,而不是直接创建UserModel
				Proxy proxy = new Proxy(new UserModel()) ;
				proxy.setUserId(rs.getString(1));
				proxy.setName(rs.getString(2));
				userList.add(proxy) ;
			}
			rs.close();
			pstmt.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			conn.close();
		}
		return userList;
	}

	/**
	 * 取得数据库连接
	 * @return
	 * @throws Exception
	 */
	private Connection getConnection() throws Exception {
		Class.forName(DBDRIVER) ;
		Connection con = DriverManager.getConnection(DBURL, DBUSER, PASSWORD);
		return con;
	}
	
}
